//
//  HWQQGameTypeController.swift
//  HWanGame
//
//  Created by 王昌健 on 2023/6/2.
//  Copyright © 2023 94hwan. All rights reserved.
//

import UIKit
import JXSegmentedView
class HWQQGameTypeController: HWBaseViewController {
    var type:String = "0"
    
    var tableView:UITableView!
    var tableViewProtocol = HWQQGameTypeProtocol()
    var httpManager = HWQQGameTypeHttpManager()
    var modelArr = NSMutableArray()
    
    var sdkImp = QMASDKDelegateImp()
    var contextImp = QMAContextDelegateImp()
    var downloadImp = QMADownloadDelegateImp()
    var cacheImp = QMACacheDelegateImp()
    var channelImp = QMANetworkChannelDelegateImp()
    var uiImp = QMAUIDelegateImp()
    var shareImp = QMAShareDelegateImp()
    var environmentImp = QMAAppEnvironmentDelegateImp()
    var startImp = QMAStartUpProtocolImp()
    var tritonImp = QMATritonSDKDelegateImp()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        qqGameInit()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        addRefresh()
        
        addAction()
        
    }

}

extension HWQQGameTypeController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

@objc extension HWQQGameTypeController {
    @objc func qqGameInit() -> Void {
        QQMiniAppSDKManager.sharedInstance().sdkDelegate = self.sdkImp  // 必须实现,宿主必要信息
        QQMiniAppSDKManager.sharedInstance().downloadDelegate = self.downloadImp  // 必须实现,资源下载相关
        QQMiniAppSDKManager.sharedInstance().cacheDelegate = self.cacheImp;    //  建议实现,缓存相关
        QQMiniAppSDKManager.sharedInstance().advDelegate = self.sdkImp       // 非必须实现,小游戏内商业化广告
        QQMiniAppSDKManager.sharedInstance().channelDelegate = self.channelImp  // ,必须实现, 请求小游戏下载包
        QQMiniAppSDKManager.sharedInstance().contextDelegate = self.contextImp  // 非必要实现,但是会影响部分功能
        QQMiniAppSDKManager.sharedInstance().uiDelegate = self.uiImp            // 非必要实现,但是会影响部分功能
        QQMiniAppSDKManager.sharedInstance().shareDelegate = self.shareImp      // 非必要实现,但是影响分享功能
        QQMiniAppSDKManager.sharedInstance().appEnvDelegate = self.environmentImp    // 非必要实现,当前SDK运行环境
        QQMiniAppSDKManager.sharedInstance().startUpDelegate = self.startImp   // 非必要实现,监控小游戏的启动过程
        TritonSDK.sharedInstance().delegate = self.tritonImp; // 非必要实现,决定小游戏的运行环境 debug(更多调试选项)或者release
        
        if ((QQMiniAppSDKManager.sharedInstance().advDelegate?.amsAppID()) != "") {
            GDTSDKConfig.registerAppId(QQMiniAppSDKManager.sharedInstance().advDelegate?.amsAppID())
        }
    }
    private func initUI() -> Void {
        self.navigationView.isHidden = true
        
        tableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        tableView.delegate = tableViewProtocol
        tableView.dataSource = tableViewProtocol
        tableView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 40
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.showsVerticalScrollIndicator = false
        view.addSubview(tableView)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
        tableView.ly_emptyView.contentViewOffset = -40
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        
        HWDataBaseManager.defaultManger.creatTable(tableName: "QQGameHistory")
    }
    
    private func initFrame() -> Void {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension HWQQGameTypeController {
    func loadData() -> Void {
        httpManager.getQQGameListHeader(sort: self.type, keyword: "") { models in
            self.tableViewProtocol.models = models
            if models.count > 0 {
                self.tableView.mj_footer?.isHidden = false
                self.modelArr.removeAllObjects()
                self.modelArr.addObjects(from: models)
            }
            self.tableView.reloadData()
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        } failure: { error in
            self.view.showHUD(title: error)
            self.modelArr.removeAllObjects()
            self.tableView.reloadData()
            self.tableView.mj_footer?.isHidden = true
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }

    }
    
    func addRefresh() -> () {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        tableView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        httpManager.getQQGameListFooter(sort: self.type, keyword: "") { models in
            self.tableView.mj_footer?.endRefreshing()
            if models.count > 0 {
                self.modelArr.addObjects(from: models)
            }
            self.tableViewProtocol.models = self.modelArr as? [HWQQGameListModel]
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}

extension HWQQGameTypeController {
    func addAction() -> Void {
        tableViewProtocol.gameButtonClick = {
            mod in
            self.httpManager.getQQGameClickUpLoad(gameId: mod.appid) { success in
                
            } failure: { errorString in
                
            }

            QQMiniAppSDKManager.sharedInstance().showApplication(withAppID: mod.appid, scene: .MAEntrySceneNone, parentVC: self, hostModel: nil)
            
            let historyModel = HWQQGameHistoryListModel()
            historyModel.id = mod.id
            historyModel.name = mod.name
            historyModel.icon = mod.icon
            historyModel.content = mod.content
            historyModel.appid = mod.appid
            historyModel.type = mod.type
            historyModel.biaoqian = mod.biaoqian
            historyModel.time = mod.time
            
            //最多只显示五条最新数据
            if HWDataBaseManager.defaultManger.selectAll().count == 5 {
                HWDataBaseManager.defaultManger.deleteWithSql(sql: "id in (select id from QQGameHistory where userId = '\(HWLocallyStoredData.getLoginUserID())' order by id ASC limit 1)") {
                    
                } failBlock: {
                    
                }
                
            }
            HWDataBaseManager.defaultManger.delete(appId: historyModel.appid) {
                
            } failBlock: {
                
            }
            HWDataBaseManager.defaultManger.insert(appId:historyModel.appid, model: historyModel) {
                
            } failBlock: {
                
            }
        }
    }
    
    @objc func openMiniGame(_ appId:String) -> Void {
        self.qqGameInit()
        QQMiniAppSDKManager.sharedInstance().showApplication(withAppID: appId, scene: .MAEntrySceneNone, parentVC: HWUniversal.getCurrentVc(), hostModel: nil)
    }
}
